#!/usr/bin/python
import cgi
import cgitb
import os
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib
from pygallib import userlib
from pygallib import picturelib

# Enable debug print
cgitb.enable()

logged_in = usersession.logged_in()
session_user = None
if logged_in:
  session_user = usersession.get_session_user()

headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Home")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))
layoutlib.print_page_header(menu, session_user)
print('<div id="page_body">')

if logged_in and session_user["root"] == 1:
  # Get the fields from url
  fields = cgi.FieldStorage()
  form_result = ""
  if "cmd" in fields:
    cmd = fields["cmd"].value
    user_id = None
    if "id" in fields:
      user_id = int(fields["id"].value)
    if cmd == "delete" and user_id is not None:
      userlib.delete_user(user_id)
    if len(form_result) > 0:
      print('<p>%s</p>' % form_result)

  print('<h1>Users</h1>')

  # Print user list
  (users, conn) = userlib.get_users()
  print('<table>')
  print("""
    <tr>
      <th>Username</th>
      <th>&nbsp;</th>
    </tr>
  """)
  for user in users:
    # Don't allow deletion of root
    if user["root"] == 0:
      print("""
        <tr>
          <td>%s</td>
          <td><a href="admin_user_list.cgi?cmd=delete&id=%d">Delete</a></td>
        </tr>
      """ % (user["username"], user["user_id"]))
  print('</table>')
  users.close()
  conn.close()
else:
  print('<p>You need admin privileges.</p>')

print('</div>')
layoutlib.print_page_close()
